<template>
  <div class="login-container" id="mianlay">

    <div class="parent">
      <div class="child">
        <div style="position: absolute;margin-top: -30px;">
          <a href="#"><img alt="" src="../../assets/cmedulogo.png" style="height: 50px;"></a>
        </div>
        <el-row>
          <el-col :span="12">
            <div class="div1">
              <h1 style="margin-left: 140px;">寄宿生信息管理系统</h1>
              <div class="info-image">
                <img alt="" src="../../assets/img/logo.jpg"
                  style="width: 415px;max-height: 350px;object-fit: contain;margin-top: 50px;">
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div style="margin-left: 80px;margin-top: 40px;">
              <h1 style="margin-left: 160px;">登录</h1>
              <el-form label-position="top" label-width="100px" :model="ruleForm" :rules="loginRules" ref="form">
                <el-form-item label="账号" prop="phone">
                  <el-input v-model="ruleForm.phone" placeholder="请输入身份证号/手机号"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password">
                  <el-input v-model="ruleForm.password" show-password placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="captcha">
                  <div style="display: flex;">
                    <el-input v-model="ruleForm.captcha" placeholder="请输入验证码" style="width: 250px;">

                    </el-input>
                    <img style="cursor: pointer;width: 100px;height: 40px;display: flex;" @click="init()"
                      :src="imgNumber" />
                  </div>

                </el-form-item>
                <el-form-item>
                  <el-button
                    style="width:360px;height: 50px;background-color: #ff4d4f !important;;color: #fff;font-size: 16px;"
                    @keyup.enter="keyDown" @click="onSubmit">登 录</el-button>
                  <div style="color: #ff4d4f !important;;cursor: pointer;" @click="forgetPsw">忘记密码？</div>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>
      </div>

    </div>
    <div style="width: 100%;position: absolute;height: 50px;bottom: 12%;text-align: center;color: #aaa;">
      Copyright 上海市崇明区教育局 2023<a @click="goUrl" style="color: #ff4d4f !important;;">https://home.cmjy.sh.cn</a>
    </div>



    <!-- 忘记密码弹出层 -->
    <a-modal v-model="visible" title="忘记密码" :footer="null">
      <a-steps :current="current">
        <a-step>
          <!-- <span slot="title">Finished</span> -->
          <template slot="title"> 手机号验证 </template>
        </a-step>
        <a-step title="填写新密码" />
      </a-steps>
      <a-form-model :layout="layout" v-bind="formItemLayout" :model="ruleForm" :rules="rules" ref="ruleForm"
        v-show="current == 1">
        <a-form-model-item label="手机号" prop="phone">
          <a-input v-model="ruleForm.phone" allowClear placeholder="请输入手机号"></a-input>
        </a-form-model-item>
        <!-- <a-form-model-item label="图片验证码" prop="captcha">
          <div style="display: flex">
            <a-input
              autocomplete="autocomplete"
              allowClear
              v-model="ruleForm.captcha"
              placeholder="请输入右侧图形中的验证码"
              v-decorator="[
                'captcha',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入右侧图形中的验证码',
                      whitespace: true,
                    },
                  ],
                },
              ]">
            </a-input>
            <img class="captcha-ys" @click="init2()" :src="imgNumber2" />
          </div>
        </a-form-model-item> -->
        <a-form-model-item label="图片验证码" prop="captcha">
          <a-row :gutter="6" class="margin-l">
            <a-col :span="14">
              <a-input autocomplete="autocomplete" allowClear v-model="ruleForm.captcha" placeholder="请输入右侧图形中的验证码"
                v-decorator="[
            'captcha',
            {
              rules: [
                {
                  required: true,
                  message: '请输入右侧图形中的验证码',
                  whitespace: true,
                },
              ],
            },
          ]">
              </a-input>
            </a-col>
            <a-col :span="10">
              <img class="captcha-ys" @click="init2()" :src="imgNumber2" />
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item label="短信验证码" prop="code">
          <a-row :gutter="6" class="margin-l">
            <a-col :span="14">
              <a-input v-model="ruleForm.code" allowClear placeholder="请输入手机短信验证码">
              </a-input>
            </a-col>
            <a-col :span="10">
              <a-button class="captcha-button" :disabled="isShow" @click="getMessage()">{{ messageInfo }}</a-button>
            </a-col>
          </a-row>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="buttonItemLayout.wrapperCol">
          <a-button type="primary" @click="next"> 下一步 </a-button>
        </a-form-model-item>
      </a-form-model>
      <a-form-model :layout="layout" v-bind="formItemLayout" :model="ruleForm" :rules="rules" ref="ruleForm"
        v-show="current == 2">
        <a-form-model-item label="新密码" prop="password">
          <a-input v-model="ruleForm.password" allowClear placeholder="请输入新密码" type="password"></a-input>
        </a-form-model-item>
        <a-form-model-item label="确认新密码" prop="newpassword">
          <a-input class="margin-l" v-model="ruleForm.newpassword" allowClear placeholder="请再次输入密码"
            type="password"></a-input>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="buttonItemLayout.wrapperCol">
          <a-button type="primary" @click="onSubmit3"> 提交 </a-button>
          <a-button v-if="current > 0" @click="prev" style="margin: 0 6px">上一步</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { getRoutesConfig } from "@/services/user"
import { setAuthorization } from "@/utils/request";
import { loadRoutes } from "@/utils/routerUtil";
import { mapMutations } from "vuex";
import httplogin from "../../api/login";
import application from "@/api/application";
// import options from '../../router/config'

import CryptoJS from "crypto-js";
export default {
  name: "Login",
  data() {
    return {
      timer: null,
      logging: false,
      autoLogin: true,
      visible: false,
      current: 1,
      vcode: "",
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      other: "",
      ruleForm: {
        phone: "",
        password: "",
        code: "",
        captcha: "",
        newpassword: "",
      },

      loginRules: {
        phone: [
          { required: true, message: "请输入身份证号/手机号", trigger: "blur" },

        ],

        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        // captcha: [
        //   { required: true, message: "请输入验证码", trigger: "blur" },
        // ],
      },

      messageInfo: "获取验证码",
      isShow: false,
      error: "",
      form: this.$form.createForm(this),
      state: null,
      imgNumber: null,
      imgNumber2: null,
      forgetState: "",
      imgIcon: [],
      appInfo: [],
      layout: "horizontal",
      status: 0,
      codeUrl: ''
    };
  },
  computed: {
    systemName() {
      return this.$store.state.setting.systemName;
    },
    formItemLayout() {
      return this.layout === "horizontal"
        ? {
          labelCol: { span: 4 },
          wrapperCol: { span: 14 },
        }
        : {};
    },
    buttonItemLayout() {
      return this.layout === "horizontal"
        ? {
          wrapperCol: { span: 14, offset: 4 },
        }
        : {};
    },
  },
  mounted() {
    window.addEventListener('keydown', this.keyDown);
    const url = window.location.href;
    if (url.indexOf("redirect_uri") > 0) {
      var redirect_uri = this.getUrlParams2(url).redirect_uri;
    }
    if (redirect_uri) {
      var s = CryptoJS.enc.Base64url.parse(redirect_uri).toString(
        CryptoJS.enc.Utf8
      );
      localStorage.setItem("redirect_uri", s);
    }

    if (url.indexOf("code") > 0) {
      this.codeUrl = this.getUrlParams2(url).code;
      this.getTokenForCOde(this.codeUrl)
    }

    // this.init();
    // this.initThirdLogin();
    //账号密码默认值
    this.form.setFieldsValue({
      name: "",
      password: "",
      captcha: "",
    });
  },
  //销毁事件
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    async getTokenForCOde(code) {
      const data = {
        code: code,
      }
     await httplogin.getcodeToken(data).then((res) => {
        if (res.data.code == 2000) {
          const { token, ym } = res.data.data.data;
          let now = new Date(new Date(new Date().getTime() + 30 * 60 * 1000));
          setAuthorization({
            token: token,
            expireAt: now,
          });

          this.isBInddingding();
        }
      }).catch((err) => {

      });
    },
    async keyDown(e) {
      //如果是回车则执行登录方法
      if (e.keyCode == 13) {
        //需要执行的登录方法
        this.onSubmit()
      }
    },
    forgetPsw() {
      this.visible = true;
      this.init2();
    },
    validateBtn() {
      //倒计时
      let that = this;
      let time = 90;

      //默认样式，防止快速点击好几次

      this.messageInfo = time + "秒后重试";

      that.timer = setInterval(() => {
        if (time == 0) {
          clearInterval(that.timer);

          that.messageInfo = "获取验证码";

          that.isShow = false;
        } else {
          that.messageInfo = time + "秒后重试";

          that.isShow = true;

          time--;
        }
      }, 1000);
    },

    getMessage() {
      //忘记密码获取手机验证码回调
      if (this.ruleForm.phone == "") {
        this.$message.error("手机号不能为空", 3);
      } else {
        if (this.ruleForm.captcha == "") {
          this.$message.error("验证码不能为空", 3);
          return;
        }

        var param = {
          mobile: this.ruleForm.phone,
          state: this.forgetState,
          captcha: this.ruleForm.captcha,
        };

        httplogin.getMessaageCode(param).then((res) => {
          if (res.data.code == 0) {
            this.vcode = res.data.data;
            this.validateBtn();
          } else if (res.data.code == 2) {
            this.$message.error("验证码错误");
            this.messageInfo = "获取验证码";
            this.isShow = false;
            clearInterval(this.timer);
            this.init2();
          }
        });
      }
    },
    next() {
      this.current++;
    },
    prev() {
      this.current--;
    },
    onSubmit3() {
      if (this.ruleForm.password == "" || this.ruleForm.newpassword == "") {
        this.$message.error("密码不能为空", 3);
      }
      if (this.ruleForm.password != this.ruleForm.newpassword) {
        this.$message.error("两次密码输入不一致", 3);
        return;
      }
      let data = {
        password: this.ruleForm.password,
        confirmPassword: this.ruleForm.newpassword,
        state: this.forgetState,
        otpCaptcha: this.ruleForm.code,
        userId: this.vcode.userId,
        username: this.vcode.username,
      };
      httplogin.updatePassword(data).then((res) => {
        if (res.data.code == 0) {
          this.$message.success("密码修改成功", 3);
        }
        this.visible = false;
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
    },
    getUrlParams2(url) {
      if (url.indexOf("?") > 0) {
        let urlStr = url.split("?")[1];
        const urlSearchParams = new URLSearchParams(urlStr);
        const result = Object.fromEntries(urlSearchParams.entries());
        return result;
      }
    },
    goUrl() {
      window.open("https://home.cmjy.sh.cn");
    },
    skipThirdLogin(val) {
      let provider = this.appInfo[val].provider;
      httplogin.goThirdLogin(provider).then((res) => {
        if (res.data.code == 0) {
          // this.$router.push({ path: "/callback/" + provider })
          window.location.href = res.data.data;
        }
      });
    },
    initThirdLogin() {
      httplogin.thirdLogin(true, "").then((res) => {
        if (res.status == 200) {
          this.imgIcon = res.data.data.socials.providers;
          this.appInfo = res.data.data.socials.providers;
        }
      });
    },
    ...mapMutations("account", ["setUser", "setPermissions", "setRoles"]),
    async onSubmit() {

      // this.form.validateFields((err) => {
      //   if (!err) {
      this.logging = true;
      // const username = this.form.getFieldValue("name");
      // const password = this.form.getFieldValue("password");
      // this.captcha = this.form.getFieldValue("captcha");
      const data = {
        "avatar": "",
        "createBy": 0,
        "createTime": "",
        "delFlag": 0,
        "email": "",
        "gllx": "",
        "id": 0,
        "jb": "",
        "menus": [
          {
            "children": [
              {
                "children": [
                  {}
                ],
                "component": "",
                "createBy": 0,
                "createTime": "",
                "delFlag": 0,
                "icon": "",
                "id": 0,
                "menuName": "",
                "parentId": 0,
                "path": "",
                "perms": "",
                "remark": "",
                "status": "",
                "updateBy": 0,
                "updateTime": "",
                "visible": ""
              }
            ],
            "component": "",
            "createBy": 0,
            "createTime": "",
            "delFlag": 0,
            "icon": "",
            "id": 0,
            "menuName": "",
            "parentId": 0,
            "path": "",
            "perms": "",
            "remark": "",
            "status": "",
            "updateBy": 0,
            "updateTime": "",
            "visible": ""
          }
        ],
        "nickName": "",
        "password": "",
        "phonenumber": "",
        "role": "",
        "sex": "",
        "status": "",
        "updateBy": 0,
        "updateTime": "",
        "userName": "",
        "userType": "",
        "userid": "00001112" //00000001  区级 //"00001744" // 校级 00001112
      };
      httplogin
        .getlogin(data)
        .then((res) => {
          if (res.data.code == 2000) {
            const {
              token
            } = res.data.data.data;
            //保存token 以及token失效时间
            let now = new Date(new Date(new Date().getTime() + 30 * 60 * 1000));
            //设置时间
            // now.setMinutes(now.getMinutes() + expired / 10);
            setAuthorization({
              token: token,
              expireAt: now,

            });
            // const op = require('../../router/config').default
            // this.setUser(displayName);
            // this.setPermissions(displayName);
            // this.setRoles(type);
            // localStorage.setItem("loginuserId", id);
            this.isBInddingding();

            // console.log(options.routes)
            // loadRoutes(op.routes)

            // console.log(this.$router.options.routes)

            // 获取路由配置
          } else if (res.data.code == 2) {
            this.$message.error(
              res.data.message ? res.data.message : "验证码失效",
              3
            );
            this.logging = false;
            this.init();
          }
        })
        .catch((err) => {
          this.$message.error("用户名或密码错误");
          this.logging = false;
          this.init();
        });
      // }
      // });
    },
    async formatDataRoute() {
      // let routerArr = [];
      // let obj = {
      //   children: [],
      //   router: "root",
      // };
      // const res = await httplogin.getMenuTree();
      // for (let index = 0; index < res.data.length; index++) {
      //   if (this.status == 0 && res.data[index].id == 113) {
      //     res.data.splice(index, 1);
      //     break;
      //   }
      // }


      // obj.children = res.data;
      // routerArr.push(obj);
      // await loadRoutes(routerArr);
      await this.$router.push("/loading").catch(() => { });
    },
    async isBInddingding() {
      // let id = localStorage.getItem("loginuserId");
      // let param =
      //   "%7Bcreate_user_id%3A" + id + "%2Cfk_adhibition_id%3Adingding%7D";
      // let res = await application.getLists(param);
      // if (res.data.errcode == 0 && res.data.rows.length > 0) {
      //   this.status = 1;
      // }
      this.formatDataRoute();
    },
    //刷新验证码
    init2() {
      httplogin
        .getInitKey()
        .then((result) => {
          const { state } = result.data.data;
          if (result.status == 200) {
            this.state = state;
            const data = {
              state,
            };
            httplogin
              .getNumber(data)
              .then((res) => {
                const { image, state } = res.data.data;
                if (res.status == 200) {
                  this.imgNumber2 = image;
                  this.forgetState = state;
                } else {
                  this.imgNumber2 = null;
                }
              })
              .catch((err) => {
                console.error(err);
              });
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    //刷新验证码
    init() {
      httplogin
        .getInitKey()
        .then((result) => {
          const { state } = result.data.data;
          if (result.status == 200) {
            this.state = state;
            const data = {
              state,
            };
            httplogin
              .getNumber(data)
              .then((res) => {
                const { image } = res.data.data;
                if (res.status == 200) {
                  this.imgNumber = image;
                } else {
                  this.imgNumber = null;
                }
              })
              .catch((err) => {
                console.error(err);
              });
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
  },
};
</script>

<style lang="less" scoped>
.formcenter {
  position: absolute;
  min-height: 600px;
  padding: 40px 0;
  width: 1000px;
  display: flex;
  margin: 0 auto;
  flex-direction: row;
  background: #fff;
}

.div1 {
  // display: flex;
  // width: 500px;
  padding: 10px;
  margin-top: 40px;
  // flex: 1;
  // flex-direction: column;
  // border-right: 1px solid #eee;
}

.info-image {
  display: flex;
  width: 100%;
  flex: 1;
  justify-content: center;
  align-items: center;
}

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.child {
  position: absolute;
  // top: 15%;
  // left: 22%;
  // margin-top: -50px;
  // margin-left: -50px;
  min-height: 600px;
  padding: 40px 0;
  width: 1000px;
  display: flex;
  margin: 0 auto;
  flex-direction: row;
  background: #fff;
  box-shadow: 0 5px 30px #5f6f7c17
}

.login-container {
  display: flex;
  align-items: stretch;
  height: 100vh;

  .logo {
    flex: 3;
    background: rgba(38, 72, 176) url(../../assets/common/login_back.png) no-repeat center / cover;
    border-top-right-radius: 60px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    padding: 0 100px;

    .icon {
      background: url(../../assets/common/logo.png) no-repeat 70px center / contain;
      width: 300px;
      height: 50px;
      margin-bottom: 50px;
    }

    p {
      color: #fff;
      font-size: 18px;
      margin-top: 20px;
      width: 300px;
      text-align: center;
    }
  }





}
</style>
